#coding:utf-8
import json
import time
import requests
import hmac
import base64
import hashlib
import urllib.parse
from dingtalkchatbot.chatbot import DingtalkChatbot
from datetime import datetime
import os

def gettoken():
    url = 'http://192.168.3.10:8000/login'
    data = {'username': 'admin', 'pwd': '123!@#Qw'}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    with requests.Session() as s:
        # 禁用自动重定向以检查登录响应
        login_resp = s.post(url, data=data, headers=headers, allow_redirects=False)
        # 检查登录是否成功（如302重定向）
        if login_resp.status_code in (301, 302, 303, 307):
           # print("Login likely successful, redirecting to:", login_resp.headers['Location'])
            # 手动跟随重定向
            redirect_resp = s.get('http://192.168.3.10:8000/' + login_resp.headers['Location'], allow_redirects=True)
            pro_token = s.cookies.get_dict()['pro_token']
            #print("Final Cookies:", s.cookies.get_dict()['pro_token'])
        else:
            print("Login failed. Status Code:", login_resp.status_code)
            print("Response:", login_resp.text)
    return pro_token

def getcontent(token):
    url = 'http://192.168.3.10:8000/daily/view'
    headers = {'Cookie': f'pro_token={token}',
               'content-type': 'application/json; charset=utf-8'}
    r = requests.get(url, headers=headers)
    # print(r.json())
    data = r.json()['data']
    #print(data)
    # 特殊名字列表
    special_names = {"夏玲珠", "任郭建", "胡晓平"}

    # 用于记录名字出现的次数
    name_count = {}

    # 用于记录筛选结果
    filtered_results = []

    # 第一次遍历：统计每个名字出现的次数
    for item in data:
        if item["iswork"] == 0 and item["isidle"] == 0:
            realname = item["realname"]
            if realname in name_count:
                name_count[realname] += 1
            else:
                name_count[realname] = 1

    # 第二次遍历：根据条件筛选结果
    for item in data:
        if item["iswork"] == 0 and item["isidle"] == 0:
            realname = item["realname"]
            # 如果是特殊名字且出现次数大于1，或者非特殊名字且未记录过
            if (realname in special_names and name_count[realname] > 1) or (
                    realname not in special_names and name_count[realname] == 1):
                if realname not in filtered_results:
                    filtered_results.append(realname)

    # 输出结果
    #print(json.dumps(filtered_results, ensure_ascii=False, indent=4))
    #先移除杨总，等他来上班
    # remove_name = '杨进庆'
    # if remove_name in filtered_results:
    #     filtered_results.remove(remove_name)
    delimiter = ", "  # 定义分隔符
    result = delimiter.join(filtered_results)
    return result

def getcontent2(token):
    url = 'http://192.168.3.10:8000/daily/view'
    headers = {'Cookie': f'pro_token={token}',
               'content-type': 'application/json; charset=utf-8'}
    r = requests.get(url, headers=headers)
    # print(r.json())
    data = r.json()['data']
    #print(data)

    # 用于记录筛选结果
    filtered_results = []

    # 第一次遍历：统计每个名字出现的次数
    for item in data:
        if item["iswork"] == 0 and item["isidle"] == 0:
            realname = item["realname"]
            filtered_results.append(realname)


    # 输出结果
    #print(json.dumps(filtered_results, ensure_ascii=False, indent=4))
    #先移除杨总，等他来上班
    remove_name = '夏玲珠PM'
    if remove_name in filtered_results:
        filtered_results.remove(remove_name)
    delimiter = ", "  # 定义分隔符
    result = delimiter.join(filtered_results)
    #print(result)
    return result

def getDingtalkRemind(result):
    timestamp = str(round(time.time() * 1000))

    robot_webhook = "https://oapi.dingtalk.com/robot/send?access_token=781ba6ff8c616278b61c5250e622dfcb645874a7abfd85fc5d6f61136e5df491"
    secret = "SECaf15bbd8742641183d1b8c790125f6ddb915a05ddcb98e4061218e3055249cde"
    #robot_webhook = "https://oapi.dingtalk.com/robot/send?access_token=5ee32a1beed3c7810e7a2d7d94db55ad48144ce25456716171a7aebf82d6883f"
    #secret = "SECb5273c8838985e8638c5681a3a170fa79ff2178ade24065142d32989819ad28f"

    secret_enc = secret.encode("utf-8")
    string_to_sign = "{}\n{}".format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode("utf-8")
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    webhook = f"{robot_webhook}&timestamp={timestamp}&sign={sign}"

    msg_text = "以下同事未写日报，请按时完成日报，大家互相提醒下：\n" + result

    msgs = DingtalkChatbot(webhook)

    '''
    at_mobiles: 被@的人的手机号 eg: ['138xxxxxxxx', '136xxxxxxxx']
    is_at_all : 是否 @ 全员
    '''
    states = msgs.send_text(msg=(msg_text), at_mobiles=[], is_at_all=True)

    #写入日志
    with open('dailyReport.txt','a', encoding="utf-8") as file:
        # 获取当前日期和时间
        now = datetime.now()
        file.write(now.strftime("%Y-%m-%d %H:%M:%S")+'\n')
        file.write(msg_text+'\n')
        file.write(f"钉钉机器人消息状态: {states}"+'\n')


    #print(f"钉钉机器人消息状态: {states}")

if __name__ == "__main__":
    pro_token = gettoken()
    result = getcontent2(pro_token)
    if result:
        getDingtalkRemind(result)
    else:
        print("今天很棒，大家都填写了日报！")











